package com.tpc.server.systeme.utils;

import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.Locale;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.Flags.Flag;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Store;
import javax.servlet.http.HttpServletRequest;

/**
 * @version 0.0.1
 * @author frederic.fortin
 * @modified 2011-03-17
 */
public class MailManager {

    private SecuriteManager objSecurite;

    public MailManager() {
        
    }

    public int checkMessages(HttpServletRequest request) {
        try {
            objSecurite = new SecuriteManager(request);

            Properties props = new Properties();

            Session sessionMail = Session.getDefaultInstance(props, null);

            Store store = sessionMail.getStore("pop3");

            store.connect("pop.prometour.com","atlas@prometour.com","123atlas23*");

            Folder folder = store.getFolder("INBOX");
            folder.open(Folder.READ_WRITE);

            Message message[] = folder.getMessages();

            int nbrMsg = message.length;
            DateManager dateM = new DateManager();

            for (int i=0, n=message.length; i<n; i++) {
                int[] ids = extractContact(message[i].getRecipients(Message.RecipientType.TO));
                String bodyText = extractBody(message[i]);
                if (ids != null) {
                    SimpleDateFormat sdfyyyymmddHHMMSS = new SimpleDateFormat(objSecurite.getProperties().getProperty("DATE_FORMAT_DATABASE"),Locale.US);
                    String sentDate = sdfyyyymmddHHMMSS.format(message[i].getSentDate());
                    String sqlInsertTask = "INSERT INTO task SET subject = ?,description = ?,date = ?,created_date = ?,created_by = ?,modified_date = ?,modified_by = ?,life = ?";
                    String[] insertOrgParameter = {message[i].getSubject(),bodyText,sentDate,dateM.NOW(),new Integer(ids[2]).toString(),dateM.NOW(),new Integer(ids[2]).toString(),objSecurite.getProperties().getProperty("ENABLE")};
                    objSecurite.getDataBaseManager().executeUpdate(sqlInsertTask, insertOrgParameter);
                    int taskId = objSecurite.getDataBaseManager().getLastInsertedId();

                    // BIND TASK ACTION
                    String sqlInsertAction = "INSERT INTO task_has_key_action SET taskId = ?, tagkeyId = ?";
                    String[] ParameterAction = {new Integer(taskId).toString(),objSecurite.getProperties().getProperty("TASK_ACTION_EMAIL")};
                    objSecurite.getDataBaseManager().executeUpdate(sqlInsertAction,ParameterAction);

                    // BIND TASK STATUS
                    String sqlInsertTaskStatus = "INSERT INTO task_has_key_status SET tagkeyId = ?, taskId = ?";
                    String[] Parameters = {objSecurite.getProperties().getProperty("TASK_STATUS_DONE"),new Integer(taskId).toString()};
                    objSecurite.getDataBaseManager().executeUpdate(sqlInsertTaskStatus, Parameters);

                    // SHOULD WE BIND TASK TO CONTACT
                    String sqlInsertTaskContact = "INSERT INTO user_contact_has_task SET userId = ?, taskId = ?";
                    String[] ParamTaskContact = {new Integer(ids[0]).toString(),new Integer(taskId).toString()};
                    objSecurite.getDataBaseManager().executeUpdate(sqlInsertTaskContact,ParamTaskContact);

                    // BIND TASK TO ORGANISATION
                    String sqlInsertTaskOrganisation = "INSERT INTO organization_has_task SET organizationId = ?, taskId = ?";
                    String[] ParamTaskOrg = {new Integer(ids[1]).toString(),new Integer(taskId).toString()};
                    objSecurite.getDataBaseManager().executeUpdate(sqlInsertTaskOrganisation,ParamTaskOrg);
                    
                    // BIND TASK TO RESSOURCE
                    String sqlInsertTaskRessource = "INSERT INTO user_ressource_has_task SET resourceId = ?, taskId = ?";
                    String[] ParamTaskRessource = {new Integer(ids[2]).toString(),new Integer(taskId).toString()};
                    objSecurite.getDataBaseManager().executeUpdate(sqlInsertTaskRessource,ParamTaskRessource);
                    
                    message[i].setFlag(Flag.DELETED,true);
                }
            }

            objSecurite.getDataBaseManager().closeConnection();
            folder.close(true);
            store.close();

            return nbrMsg;
        }
        catch(Exception e) {

            return -1;
        }
    }

    private int[] extractContact(Address[] recipients) {
        try {
            int[] ids = {-1,-1,-1};
            String AtlasContact = null;
            if (recipients != null) {
                AtlasContact = recipients[0].toString();
            }
            if (AtlasContact != null) {
                if (AtlasContact.indexOf("<") > -1) {
                    String[] finalto = AtlasContact.split("<");
                    AtlasContact = finalto[1].substring(0,finalto[1].length()-1);
                }
            }

            String sqlFrom = "SELECT user_has_url.userId,organisation_has_contact.organisationId,user_ressource_has_organisation.ressourceId FROM url,user_has_url,organisation_has_contact,"
                    + "user_ressource_has_organisation WHERE url = ? AND url.id = user_has_url.urlId AND user_has_url.userId = organisation_has_contact.userId AND "
                    + "organisation_has_contact.organisationId = user_ressource_has_organisation.organisationid LIMIT 0,1";
            String[] paramFrom = {AtlasContact};
            ResultSet rsContact =  objSecurite.getDataBaseManager().executeQuery(sqlFrom,paramFrom);
            if (rsContact != null) {
                if (rsContact.next()) {
                    ids[0] = rsContact.getInt("user_has_url.userId");
                    ids[1] = rsContact.getInt("organisation_has_contact.organisationId");
                    ids[2] = rsContact.getInt("user_ressource_has_organisation.ressourceId");
                }
            }

            return ids;
        }
        catch(Exception e) {
            return null;
        }
    }

    private String extractBody(Message message) {
        String strBody = "text";
        try {
            strBody = (String) message.getContent();
        }
        catch (Exception i) {
System.out.print(i.getMessage());
        }
        return strBody;
    }

    private void extractParts(Multipart mPart) {
        
    }

}
